package com.ruoyi.project.wenyanwen.generatelog.service.impl;

import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.Md5Utils;
import com.ruoyi.common.utils.OSSUtil;
import com.ruoyi.common.utils.PackageHelper;
import com.ruoyi.common.utils.SizeUtil;
import com.ruoyi.common.utils.text.Convert;
import com.ruoyi.framework.aspectj.lang.annotation.DataSource;
import com.ruoyi.framework.aspectj.lang.enums.DataSourceType;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.datasource.DynamicDataSourceContextHolder;
import com.ruoyi.project.wenyanwen.generate.domain.DbGenerate;
import com.ruoyi.project.wenyanwen.generate.mapper.DbGenerateMapper;
import com.ruoyi.project.wenyanwen.generatelog.domain.DbGenerateLog;
import com.ruoyi.project.wenyanwen.generatelog.mapper.DbGenerateLogMapper;
import com.ruoyi.project.wenyanwen.generatelog.service.IDbGenerateLogService;
import jodd.io.FileUtil;
import jodd.io.ZipUtil;
import jodd.util.MimeTypes;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 数据包浏览Service业务层处理
 *
 * @author shixiangwen
 * @date 2020-09-27
 */
@Service
@DataSource(DataSourceType.KKWENYANWEN)
public class DbGenerateLogServiceImpl implements IDbGenerateLogService {

    protected static Log logger = LogFactory.getLog(DbGenerateLogServiceImpl.class);


    private final static String RESOURCE_OSS_DOMAIN = "http://resource.kkc.cdn.youzhi.net/";

    @Autowired
    private DbGenerateLogMapper dbGenerateLogMapper;

    @Autowired
    private DbGenerateMapper dbGenerateMapper;


    /**
     * 查询数据包浏览
     *
     * @param id 数据包浏览ID
     * @return 数据包浏览
     */
    @Override
    public DbGenerateLog selectDbGenerateLogById(Long id) {
        return dbGenerateLogMapper.selectDbGenerateLogById(id);
    }

    /**
     * 查询数据包浏览列表
     *
     * @param dbGenerateLog 数据包浏览
     * @return 数据包浏览
     */
    @Override
    public List<DbGenerateLog> selectDbGenerateLogList(DbGenerateLog dbGenerateLog) {
        return dbGenerateLogMapper.selectDbGenerateLogList(dbGenerateLog);
    }

    /**
     * 新增数据包浏览
     *
     * @param dbGenerateLog 数据包浏览
     * @return 结果
     */
    @Override
    public int insertDbGenerateLog(DbGenerateLog dbGenerateLog) {
        return dbGenerateLogMapper.insertDbGenerateLog(dbGenerateLog);
    }

    /**
     * 修改数据包浏览
     *
     * @param dbGenerateLog 数据包浏览
     * @return 结果
     */
    @Override
    public int updateDbGenerateLog(DbGenerateLog dbGenerateLog) {
        return dbGenerateLogMapper.updateDbGenerateLog(dbGenerateLog);
    }

    /**
     * 删除数据包浏览对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteDbGenerateLogByIds(String ids) {
        return dbGenerateLogMapper.deleteDbGenerateLogByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除数据包浏览信息
     *
     * @param id 数据包浏览ID
     * @return 结果
     */
    @Override
    public int deleteDbGenerateLogById(Long id) {
        return dbGenerateLogMapper.deleteDbGenerateLogById(id);
    }

    @Override
    public int upload(Long id) {
        DbGenerateLog dbGenerateLog = dbGenerateLogMapper.selectDbGenerateLogById(id);
        if (dbGenerateLog.getUploadStatus() == 1) {
            throw new BusinessException("当前文件正在上传");
        }
        if (dbGenerateLog.getUploadStatus() == 2) {
            throw new BusinessException("当前文件已经上传");
        }

        dbGenerateLog.setUploadStatus(1);
        dbGenerateLogMapper.updateDbGenerateLog(dbGenerateLog);

        new Thread(new Runnable() {
            @Override
            public void run() {

                DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.KKWENYANWEN.name());
                logger.info("datasource type[" + DynamicDataSourceContextHolder.getDataSourceType() + "]");
                DbGenerate query = new DbGenerate();
                query.setDbName(dbGenerateLog.getDbName());
                List<DbGenerate> dbGenerates = dbGenerateMapper.selectDbGenerateList(query);
                DbGenerate dbGenerate = dbGenerates.get(0);
                try {
                    String localFileName = RuoYiConfig.getPackagePath() + dbGenerateLog.getFileName();
                    String localShortName = RuoYiConfig.getPackagePath() + "tmp/" + dbGenerate.getDbName();
                    logger.info("copy [" + localFileName + "] to [" + localShortName + "]");
                    FileUtil.copy(localFileName, localShortName);
                    String localZipFileName = localShortName + ".zip";
                    logger.info("zip file[" + localShortName + "] to [" + localZipFileName + "]");
                    ZipUtil.zip(localShortName);
                    byte[] bytes = FileUtil.readBytes(localZipFileName);
                    String md5 = Md5Utils.md5(bytes);
                    long size = bytes.length;
                    String uploadPath = PackageHelper.getUploadPath(dbGenerate.getApp(), dbGenerate.getResName(), dbGenerate.getVersion());
                    logger.info("upload file[" + localZipFileName + "] to [" + uploadPath + "], size[" + SizeUtil.sizeFormat(size) + "], md5[" + md5 + "]");
                    OSSUtil.upload("kkcresource", bytes, uploadPath, MimeTypes.lookupMimeType(".zip"));
                    String downloadPath = RESOURCE_OSS_DOMAIN + uploadPath;
                    PackageHelper.syncToResupgrade(dbGenerate.getApp(), downloadPath, size, md5, dbGenerate.getResName(), dbGenerateLog.getVersion(), dbGenerate.getSupportVersion());

                    FileUtil.delete(localShortName);
                    FileUtil.delete(localZipFileName);

                    logger.info("datasource type[" + DynamicDataSourceContextHolder.getDataSourceType() + "]");

                    dbGenerateLog.setUploadStatus(2);
                    dbGenerateLogMapper.updateDbGenerateLog(dbGenerateLog);

                } catch (Exception e) {

                    logger.info("datasource type[" + DynamicDataSourceContextHolder.getDataSourceType() + "]");

                    logger.error(e.getMessage(), e);
                    dbGenerateLog.setUploadStatus(-1);
                    dbGenerateLogMapper.updateDbGenerateLog(dbGenerateLog);

                } finally {
                    DynamicDataSourceContextHolder.clearDataSourceType();
                }

            }
        }).start();


        return 1;
    }

}
